import fs from 'fs'
import Config from '@/config/Config'
import ejs from 'ejs'
import { Success } from '@/core/HttpException'
import nodemailer from 'nodemailer'
const transporter = nodemailer.createTransport({
  service: Config.EMAIL_SERVICE,
  port: Config.EMAIL_PORT,
  auth: {
    user: Config.EMAIL_SENDER_NAME,
    pass: Config.EMAIL_SENDER_PASS,
  },
})

export async function sendEmail({ templatePath, validateCode, email }: any) {
  const templateContent = fs.readFileSync(templatePath, 'utf-8')
  const senderName = Config.EMAIL_SENDER_NAME
  const minute = Config.SECURITY.SMSCODE_EXPIRES_IN
  const html = ejs.render(templateContent, { validateCode, senderName, minute })
  const mailOptions = {
    from: Config.EMAIL_SENDER_NAME,
    to: email,
    subject: 'Verification Code',
    html,
  }
  try {
    await transporter.sendMail(mailOptions)
  } catch (e: any) {
    throw new Success({ errorCode: -2 })
  }
}
